package club.janna.concurrency.example.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.*;

@Slf4j
public class ConcurrentHashMapExample {
    private final static int threadTotal = 5000;
    private final static int threadNum = 200;

    private static Map<Integer, Integer> set = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        final Semaphore semaphore = new Semaphore(threadNum);
        CountDownLatch countDownLatch = new CountDownLatch(threadTotal);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0; i < threadTotal; i ++) {
            final int ii = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                update(ii);
                countDownLatch.countDown();
                semaphore.release();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        log.info("size: {}", set.size());
    }

    public static void update(int i) {
        set.put(i, i);
    }
}
